package com.atguigu.tingshu.common.aspect;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.anno.GuiGuLogin;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.jar.Attributes;

@Component
@Aspect
public class GuiGuLoginAspect {
   @Autowired
   StringRedisTemplate stringRedisTemplate;

    @Around(value = "@annotation(guiGuLogin)")
    public Object around(ProceedingJoinPoint joinPoint,GuiGuLogin guiGuLogin){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        //
        boolean required = guiGuLogin.required();
        if (required) {
            if (StringUtils.isEmpty(token)) {
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            String redisLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            String userInfo = stringRedisTemplate.opsForValue().get(redisLoginKey);
            if(userInfo == null){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            UserInfo userInfo1 = JSON.parseObject(userInfo, UserInfo.class);
            AuthContextHolder.setUserId(userInfo1.getId());
            AuthContextHolder.setUsername(userInfo1.getNickname());
        }else {
          if(!StringUtils.isEmpty(token)){
              String redisLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
              String userInfo = stringRedisTemplate.opsForValue().get(redisLoginKey);
              if(userInfo != null){
                  UserInfo userInfo1 = JSON.parseObject(userInfo, UserInfo.class);
                  AuthContextHolder.setUserId(userInfo1.getId());
                  AuthContextHolder.setUsername(userInfo1.getNickname());
              }
          }
        }
        try {
            return joinPoint.proceed();
        }catch (Throwable t){
            t.printStackTrace();
            throw new RuntimeException(t);
        }finally {
            AuthContextHolder.removeUsername();
            AuthContextHolder.removeUserId();
        }
    }

 }